package org.luxor.commons.websocket.config;

import org.luxor.commons.redis.client.RedisTopicClient;
import org.luxor.commons.websocket.component.exporter.WebSocketClientExporter;
import org.luxor.commons.websocket.component.exporter.WebSocketServerExporter;
import org.luxor.commons.websocket.component.processor.WsUriValueProcessor;
import org.luxor.commons.websocket.component.session.WsSessionStorage;
import org.luxor.commons.websocket.component.session.WsSimpleSessionStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

/**
 * 开启WebSocket支持配置
 *
 * @author Mr.Yan  @date 2019/11/29
 */
@Configuration
@EnableWebSocket
@Import({WsClientProcessor.class, WsShareSessionConfig.class})
public class WebSocketAutoConfig {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketAutoConfig.class);

    @Bean
    @ConditionalOnMissingBean
    public WsUriValueProcessor wsUriProcessor(ObjectProvider<Environment> environment) {
        return new WsUriValueProcessor(environment.getIfAvailable());
    }

    @Bean
    @ConditionalOnMissingBean
    public WebSocketServerExporter serverEndpointExporter() {
        WebSocketServerExporter exporter = new WebSocketServerExporter();
        return exporter;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean(WebSocketServerExporter.class)
    public WebSocketClientExporter clientEndpointExporter(WsUriValueProcessor wsUriProcessor) {
        WebSocketClientExporter exporter = new WebSocketClientExporter(wsUriProcessor);
        return exporter;
    }

    @Bean
    @ConditionalOnMissingBean({RedisTopicClient.class, WsSessionStorage.class})
    public WsSimpleSessionStorage wsSessionStorage() {
        logger.info("Initialize wsShareSession Bean of type WsSimpleSessionStorage.");
        return new WsSimpleSessionStorage();
    }

}
